package com.example.day15_7_15_1.fragment;

import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import com.example.day15_7_15_1.ProgressEvent;
import com.example.day15_7_15_1.R;
import com.example.day15_7_15_1.util.HttpUtil;
import com.example.day15_7_15_1.view.MyProgressView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class DownloadFragment extends Fragment {

    private Button btn_start;
    private MyProgressView pro_view;
    private File file;
    private boolean down;

    public DownloadFragment() {
        // Required empty public constructor
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_download, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        EventBus.getDefault().register(this);
        initView(getView());
    }

    private void initView(View view) {
        btn_start = view.findViewById(R.id.btn_start);
        pro_view = view.findViewById(R.id.pro_view);
        btn_start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i(TAG, "onClick: ");
                if (!file.exists()){
                    try {
                        file.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if (!down){
                        initHttpDownload();
                        down = true;
                        if (pro_view.sweepAngle == 360){
                            down = false;
                        }
                    }
                }else {
                    Toast.makeText(getContext(), "文件已存在", Toast.LENGTH_SHORT).show();
                }
            }
        });
//        String path = "/sdcard/UnknowApp-1.0.apk";
        String path = Environment.getExternalStorageDirectory() + File.separator + "UnknowApp-1.0.apk";
        Log.i(TAG, "initView: " + path);
        file = new File(path);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateProgress(ProgressEvent progressEvent){
        pro_view.setProgress(progressEvent.progress);
        Log.i(TAG, "updateProgress: " + progressEvent.progress);
        if (progressEvent.progress == 100){
            Toast.makeText(getContext(), "下载完成", Toast.LENGTH_SHORT).show();
        }
    }


    private String url = "http://yun918.cn/study/public/res/UnknowApp-1.0.apk";
    private static final String TAG = "MyService";
    private void initHttpDownload() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    int readLength = 0;
                    int readCount = 0;
                    int precent = 0;
                    URL httpUrl = new URL(url);
                    HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
                    InputStream is = conn.getInputStream();
                    int size = conn.getContentLength();
                    FileOutputStream os = new FileOutputStream(file);
                    byte[] bytes = new byte[1024 * 4];
                    while ((readLength = is.read(bytes)) != -1) {
                        os.write(bytes, 0, readLength);
                        readCount += readLength;
                        precent = readCount * 100 / size;

                        ProgressEvent progressEvent = new ProgressEvent();
                        progressEvent.progress = precent;
                        EventBus.getDefault().post(progressEvent);
                    }
                    is.close();
                    os.close();
                } catch (Exception e) {
                     e.printStackTrace();
                }
            }
        }).start();
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
